<template>
  <div class="production-reports">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>生产报表</h2>
        <p>生产数据统计分析与报表管理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="Download" @click="exportAllReports">导出全部</el-button>
        <el-button type="success" icon="Refresh" @click="refreshData">刷新数据</el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon production">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="stats-info">
                <h3>{{ overviewData.totalProduction }}</h3>
                <p>总产量</p>
                <span class="trend up">+12.5%</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon efficiency">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stats-info">
                <h3>{{ overviewData.efficiency }}%</h3>
                <p>生产效率</p>
                <span class="trend up">+3.2%</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon quality">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <h3>{{ overviewData.qualityRate }}%</h3>
                <p>合格率</p>
                <span class="trend down">-0.8%</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon cost">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stats-info">
                <h3>¥{{ overviewData.totalCost }}</h3>
                <p>生产成本</p>
                <span class="trend up">+5.1%</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 报表内容 -->
    <el-card class="reports-content">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 生产统计报表 -->
        <el-tab-pane label="生产统计" name="production">
          <div class="report-section">
            <div class="section-header">
              <h3>生产统计报表</h3>
              <div class="section-actions">
                <el-date-picker
                  v-model="productionDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="updateProductionChart"
                />
                <el-button type="primary" icon="Download" @click="exportProductionReport">导出</el-button>
              </div>
            </div>
            <div class="chart-container">
              <div ref="productionChart" class="chart"></div>
            </div>
            <el-table :data="productionTableData" stripe>
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="productName" label="产品名称" />
              <el-table-column prop="planQuantity" label="计划产量" />
              <el-table-column prop="actualQuantity" label="实际产量" />
              <el-table-column prop="completionRate" label="完成率" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.completionRate >= 100 ? 'success' : row.completionRate >= 80 ? 'warning' : 'danger'">
                    {{ row.completionRate }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="efficiency" label="生产效率" width="100" />
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 质量分析报表 -->
        <el-tab-pane label="质量分析" name="quality">
          <div class="report-section">
            <div class="section-header">
              <h3>质量分析报表</h3>
              <div class="section-actions">
                <el-select v-model="qualityProduct" placeholder="选择产品" @change="updateQualityChart">
                  <el-option label="全部产品" value="all" />
                  <el-option label="产品A" value="productA" />
                  <el-option label="产品B" value="productB" />
                  <el-option label="产品C" value="productC" />
                </el-select>
                <el-button type="primary" icon="Download" @click="exportQualityReport">导出</el-button>
              </div>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <div ref="qualityTrendChart" class="chart"></div>
              </el-col>
              <el-col :span="12">
                <div ref="defectChart" class="chart"></div>
              </el-col>
            </el-row>
            <el-table :data="qualityTableData" stripe>
              <el-table-column prop="date" label="检验日期" width="120" />
              <el-table-column prop="productName" label="产品名称" />
              <el-table-column prop="batchNo" label="批次号" />
              <el-table-column prop="inspectedQuantity" label="检验数量" />
              <el-table-column prop="qualifiedQuantity" label="合格数量" />
              <el-table-column prop="qualityRate" label="合格率" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.qualityRate >= 98 ? 'success' : row.qualityRate >= 95 ? 'warning' : 'danger'">
                    {{ row.qualityRate }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="defectType" label="主要缺陷" />
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 设备效率报表 -->
        <el-tab-pane label="设备效率" name="equipment">
          <div class="report-section">
            <div class="section-header">
              <h3>设备效率报表</h3>
              <div class="section-actions">
                <el-select v-model="equipmentWorkshop" placeholder="选择车间" @change="updateEquipmentChart">
                  <el-option label="全部车间" value="all" />
                  <el-option label="装配车间" value="assembly" />
                  <el-option label="机加车间" value="machining" />
                  <el-option label="包装车间" value="packaging" />
                </el-select>
                <el-button type="primary" icon="Download" @click="exportEquipmentReport">导出</el-button>
              </div>
            </div>
            <div ref="equipmentChart" class="chart"></div>
            <el-table :data="equipmentTableData" stripe>
              <el-table-column prop="equipmentCode" label="设备编号" />
              <el-table-column prop="equipmentName" label="设备名称" />
              <el-table-column prop="workshop" label="所属车间" />
              <el-table-column prop="runningTime" label="运行时间(h)" />
              <el-table-column prop="downTime" label="停机时间(h)" />
              <el-table-column prop="efficiency" label="设备效率" width="100">
                <template #default="{ row }">
                  <el-progress :percentage="row.efficiency" :color="getEfficiencyColor(row.efficiency)" />
                </template>
              </el-table-column>
              <el-table-column prop="oee" label="OEE" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.oee >= 85 ? 'success' : row.oee >= 70 ? 'warning' : 'danger'">
                    {{ row.oee }}%
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 成本分析报表 -->
        <el-tab-pane label="成本分析" name="cost">
          <div class="report-section">
            <div class="section-header">
              <h3>成本分析报表</h3>
              <div class="section-actions">
                <el-radio-group v-model="costAnalysisType" @change="updateCostChart">
                  <el-radio-button label="monthly">月度</el-radio-button>
                  <el-radio-button label="quarterly">季度</el-radio-button>
                  <el-radio-button label="yearly">年度</el-radio-button>
                </el-radio-group>
                <el-button type="primary" icon="Download" @click="exportCostReport">导出</el-button>
              </div>
            </div>
            <el-row :gutter="20">
              <el-col :span="16">
                <div ref="costTrendChart" class="chart"></div>
              </el-col>
              <el-col :span="8">
                <div ref="costStructureChart" class="chart"></div>
              </el-col>
            </el-row>
            <el-table :data="costTableData" stripe>
              <el-table-column prop="period" label="期间" />
              <el-table-column prop="materialCost" label="材料成本" />
              <el-table-column prop="laborCost" label="人工成本" />
              <el-table-column prop="equipmentCost" label="设备成本" />
              <el-table-column prop="overheadCost" label="制造费用" />
              <el-table-column prop="totalCost" label="总成本" />
              <el-table-column prop="unitCost" label="单位成本" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import {
  TrendCharts,
  DataAnalysis,
  CircleCheck,
  Money,
  Download,
  Refresh
} from '@element-plus/icons-vue'

// 响应式数据
const activeTab = ref('production')
const productionDateRange = ref([])
const qualityProduct = ref('all')
const equipmentWorkshop = ref('all')
const costAnalysisType = ref('monthly')

// 图表引用
const productionChart = ref(null)
const qualityTrendChart = ref(null)
const defectChart = ref(null)
const equipmentChart = ref(null)
const costTrendChart = ref(null)
const costStructureChart = ref(null)

// 概览数据
const overviewData = reactive({
  totalProduction: '125,680',
  efficiency: 87.5,
  qualityRate: 96.8,
  totalCost: '2,456,789'
})

// 生产统计表格数据
const productionTableData = ref([
  {
    date: '2024-01-15',
    productName: '产品A',
    planQuantity: 1000,
    actualQuantity: 980,
    completionRate: 98,
    efficiency: '87%'
  },
  {
    date: '2024-01-15',
    productName: '产品B',
    planQuantity: 800,
    actualQuantity: 850,
    completionRate: 106,
    efficiency: '92%'
  },
  {
    date: '2024-01-14',
    productName: '产品A',
    planQuantity: 1000,
    actualQuantity: 750,
    completionRate: 75,
    efficiency: '78%'
  }
])

// 质量分析表格数据
const qualityTableData = ref([
  {
    date: '2024-01-15',
    productName: '产品A',
    batchNo: 'BA240115001',
    inspectedQuantity: 500,
    qualifiedQuantity: 485,
    qualityRate: 97.0,
    defectType: '尺寸偏差'
  },
  {
    date: '2024-01-15',
    productName: '产品B',
    batchNo: 'BB240115001',
    inspectedQuantity: 300,
    qualifiedQuantity: 298,
    qualityRate: 99.3,
    defectType: '表面缺陷'
  }
])

// 设备效率表格数据
const equipmentTableData = ref([
  {
    equipmentCode: 'EQ001',
    equipmentName: '数控机床A',
    workshop: '机加车间',
    runningTime: 18.5,
    downTime: 1.5,
    efficiency: 92,
    oee: 87
  },
  {
    equipmentCode: 'EQ002',
    equipmentName: '装配线B',
    workshop: '装配车间',
    runningTime: 19.2,
    downTime: 0.8,
    efficiency: 96,
    oee: 91
  }
])

// 成本分析表格数据
const costTableData = ref([
  {
    period: '2024-01',
    materialCost: '1,250,000',
    laborCost: '380,000',
    equipmentCost: '150,000',
    overheadCost: '220,000',
    totalCost: '2,000,000',
    unitCost: '125.50'
  },
  {
    period: '2023-12',
    materialCost: '1,180,000',
    laborCost: '360,000',
    equipmentCost: '145,000',
    overheadCost: '210,000',
    totalCost: '1,895,000',
    unitCost: '118.75'
  }
])

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    initProductionChart()
    initQualityCharts()
    initEquipmentChart()
    initCostCharts()
  })
}

// 初始化生产统计图表
const initProductionChart = () => {
  if (!productionChart.value) return
  
  const chart = echarts.init(productionChart.value)
  const option = {
    title: {
      text: '生产趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['计划产量', '实际产量'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '计划产量',
        type: 'line',
        data: [12000, 13000, 14500, 13800, 15200, 16000]
      },
      {
        name: '实际产量',
        type: 'line',
        data: [11800, 12800, 14200, 13500, 14800, 15600]
      }
    ]
  }
  chart.setOption(option)
}

// 初始化质量分析图表
const initQualityCharts = () => {
  // 质量趋势图
  if (qualityTrendChart.value) {
    const chart = echarts.init(qualityTrendChart.value)
    const option = {
      title: {
        text: '质量趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value',
        min: 90,
        max: 100
      },
      series: [{
        name: '合格率',
        type: 'line',
        data: [96.5, 97.2, 96.8, 97.5, 96.9, 97.8]
      }]
    }
    chart.setOption(option)
  }
  
  // 缺陷分布图
  if (defectChart.value) {
    const chart = echarts.init(defectChart.value)
    const option = {
      title: {
        text: '缺陷类型分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: '60%',
        data: [
          { value: 35, name: '尺寸偏差' },
          { value: 25, name: '表面缺陷' },
          { value: 20, name: '材料问题' },
          { value: 15, name: '装配错误' },
          { value: 5, name: '其他' }
        ]
      }]
    }
    chart.setOption(option)
  }
}

// 初始化设备效率图表
const initEquipmentChart = () => {
  if (!equipmentChart.value) return
  
  const chart = echarts.init(equipmentChart.value)
  const option = {
    title: {
      text: '设备效率对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['设备效率', 'OEE'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['EQ001', 'EQ002', 'EQ003', 'EQ004', 'EQ005']
    },
    yAxis: {
      type: 'value',
      max: 100
    },
    series: [
      {
        name: '设备效率',
        type: 'bar',
        data: [92, 96, 88, 94, 90]
      },
      {
        name: 'OEE',
        type: 'bar',
        data: [87, 91, 83, 89, 85]
      }
    ]
  }
  chart.setOption(option)
}

// 初始化成本分析图表
const initCostCharts = () => {
  // 成本趋势图
  if (costTrendChart.value) {
    const chart = echarts.init(costTrendChart.value)
    const option = {
      title: {
        text: '成本趋势分析',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['材料成本', '人工成本', '设备成本', '制造费用'],
        top: 30
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '材料成本',
          type: 'line',
          stack: 'Total',
          data: [1200, 1250, 1180, 1300, 1280, 1350]
        },
        {
          name: '人工成本',
          type: 'line',
          stack: 'Total',
          data: [350, 380, 360, 390, 370, 400]
        },
        {
          name: '设备成本',
          type: 'line',
          stack: 'Total',
          data: [140, 150, 145, 155, 148, 160]
        },
        {
          name: '制造费用',
          type: 'line',
          stack: 'Total',
          data: [200, 220, 210, 230, 225, 240]
        }
      ]
    }
    chart.setOption(option)
  }
  
  // 成本结构图
  if (costStructureChart.value) {
    const chart = echarts.init(costStructureChart.value)
    const option = {
      title: {
        text: '成本结构',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [{
        type: 'pie',
        radius: '60%',
        data: [
          { value: 62.5, name: '材料成本' },
          { value: 19.0, name: '人工成本' },
          { value: 7.5, name: '设备成本' },
          { value: 11.0, name: '制造费用' }
        ]
      }]
    }
    chart.setOption(option)
  }
}

// 事件处理函数
const handleTabChange = (tabName) => {
  nextTick(() => {
    switch (tabName) {
      case 'production':
        initProductionChart()
        break
      case 'quality':
        initQualityCharts()
        break
      case 'equipment':
        initEquipmentChart()
        break
      case 'cost':
        initCostCharts()
        break
    }
  })
}

const updateProductionChart = () => {
  ElMessage.success('生产统计数据已更新')
  initProductionChart()
}

const updateQualityChart = () => {
  ElMessage.success('质量分析数据已更新')
  initQualityCharts()
}

const updateEquipmentChart = () => {
  ElMessage.success('设备效率数据已更新')
  initEquipmentChart()
}

const updateCostChart = () => {
  ElMessage.success('成本分析数据已更新')
  initCostCharts()
}

const refreshData = () => {
  ElMessage.success('数据刷新成功')
  initCharts()
}

const exportAllReports = () => {
  ElMessage.success('全部报表导出成功')
}

const exportProductionReport = () => {
  ElMessage.success('生产统计报表导出成功')
}

const exportQualityReport = () => {
  ElMessage.success('质量分析报表导出成功')
}

const exportEquipmentReport = () => {
  ElMessage.success('设备效率报表导出成功')
}

const exportCostReport = () => {
  ElMessage.success('成本分析报表导出成功')
}

const getEfficiencyColor = (efficiency) => {
  if (efficiency >= 90) return '#67c23a'
  if (efficiency >= 80) return '#e6a23c'
  return '#f56c6c'
}

// 生命周期
onMounted(() => {
  initCharts()
})
</script>

<style scoped>
.production-reports {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.production {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.efficiency {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.quality {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.cost {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info h3 {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stats-info p {
  margin: 0 0 5px 0;
  color: #909399;
  font-size: 14px;
}

.trend {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.trend.up {
  background: #f0f9ff;
  color: #1890ff;
}

.trend.down {
  background: #fff2f0;
  color: #ff4d4f;
}

.reports-content {
  min-height: 600px;
}

.report-section {
  padding: 20px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #303133;
}

.section-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.chart-container {
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .section-actions {
    justify-content: center;
  }
  
  .chart {
    height: 300px;
  }
}
</style>